<template>
  <div class="copy-campaign">
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :show-close="false"
      top="114px"
      :modal="false">
      <div class="root">
        <div class="campaign-card">
          <el-card class="campaign-card-wrapper">
            <span slot="header"><div style="float: left">复制推广系列</div><div style="float: right"><el-button
              type="text" size="mini" icon="el-icon-close" @click="dialogVisible=false" circle></el-button></div><div
              style="clear: both"></div></span>
            <el-form ref="form" :model="campaignForm" label-width="120px" :rules="rules">
              <el-form-item label="广告账户" prop="platformId">
                <el-select style="width: 100%" size="mini" v-model="campaignForm.platformId" placeholder="请选择活动账户"
                           @change="handleChangePlatform">
                  <el-option
                    v-for="item in accountList"
                    :key="item.id"
                    :value="item.platformId"
                    :label="item.name+'ID:'+item.platformId"
                    :disabled="options.campaignAppProfilePageState === 'ON'&&options.platformId !== item.platformId">
                    <span style="float: left">{{ item.name + 'ID:' + item.platformId }}</span>
                    <span v-if="options.platformId === item.platformId"
                          style="float: right; color: #8492a6; font-size: 13px">当前</span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="推广系列名称" prop="campaignName">
                <el-input size="mini" v-model="campaignForm.campaignName" @input="handleChangeName"></el-input>
              </el-form-item>
              <!--<el-form-item label="应用介绍页" prop="pageId">-->
              <!--  <el-select size="mini" v-model="campaignForm.pageId" placeholder="请选择应用介绍页"-->
              <!--             @change="handleChangeLandingPage">-->
              <!--    <el-option-->
              <!--      v-for="item in landingPageList"-->
              <!--      :key="item.value"-->
              <!--      :label="item.label+'  ID:'+item.value"-->
              <!--      :value="item.value">-->
              <!--    </el-option>-->
              <!--  </el-select>-->
              <!--</el-form-item>-->
              <el-form-item label="复制数量">
                <el-input-number size="mini" v-model="campaignForm.num" :disabled="true"></el-input-number>
              </el-form-item>
              <el-form-item label="APP">
                <el-image :src="options.os === 1 ? androidImage: iosImage"
                          style="height: 25px;width: 25px;vertical-align: middle"></el-image>&nbsp;{{ options.appName }}
                <template v-if="options.os === 2">
                  <el-checkbox v-model="campaignForm.ios14Camppaign" style="margin-left: 30px"
                               :disabled="campaignForm.platformId === ''|| true" @change="handleChangeIos14Switch">iOS
                    14
                  </el-checkbox>
                  <el-checkbox v-model="campaignForm.campaignAppProfilePageState" true-label="ON" false-label="OFF"
                               style="margin-left: 30px"
                               :disabled="!campaignForm.ios14Camppaign || true">APPO
                  </el-checkbox>
                </template>
              </el-form-item>
              <el-form-item label="预算">
                <el-input
                  size="mini"
                  v-model="campaignForm.budget" class="input-with-select" disabled
                  oninput="if(isNaN(value)){value=null} if(value.indexOf(0) === 0 && value.charAt(1) !== '.'){value=0} if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
                  <el-select style="width: 100px" id="AdGroupBudgetChange" v-model="campaignForm.budgetMode"
                             slot="prepend" placeholder="请选择"
                             :disabled="true">
                    <el-option v-for="item in budgetModeList" :key="item.value" :label="item.label"
                               :value="item.value"></el-option>
                  </el-select>
                  <template slot="append">USD</template>
                </el-input>
              </el-form-item>
              <el-form-item label="推广目标">
                应用推广
              </el-form-item>
              <el-row justify="center" type="flex" align="middle">
                <el-button size="mini" type="primary" @click="confirmCopyCampaign">确认复制</el-button>
                <!--<el-button size="mini" @click="dialogVisible = false">取消</el-button>-->
              </el-row>
              <el-collapse-transition>
                <div v-show="adGroupTableData.length>0">
                  <el-divider></el-divider>
                  <el-table
                    :data="adGroupTableData"
                    style="width: 100%">
                    <el-table-column
                      prop="adgroupName"
                      label="广告组名"
                      :show-overflow-tooltip="true">
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      width="100">
                      <template v-slot="{row,$index}">
                        <el-button type="text" @click="editAdGroup(row)">编辑</el-button>
                        <el-button type="text" @click="delAdGroup($index)">删除</el-button>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="isEdit"
                      label="状态"
                      width="100">
                    </el-table-column>
                  </el-table>
                  <el-row style="margin-top:10px" justify="center" type="flex" align="middle">
                    <el-button size="mini" type="primary" @click="submitForm" v-loading="submitCampaignLoading">发布并暂停
                    </el-button>
                  </el-row>
                </div>
              </el-collapse-transition>
            </el-form>
          </el-card>
        </div>
        <el-drawer
          :visible.sync="editAdGroupDrawer"
          :modal="false"
          size="calc(100vw - 720px)"
          :destroy-on-close="true"
          :close-on-click-modal="false"
          :with-header="false">
          <cs-drawer-container>
            <div class="edit-ad-group-box">
              <div class="edit-ad-group-box-left">
                <el-card>
                  <span slot="header">编辑广告组</span>
                  <ad-group-form ref="adGroupForm" :options="adGroupOptions"
                                 :current-account-id="campaignForm.platformId"></ad-group-form>
                </el-card>
              </div>
              <div class="edit-ad-group-box-right">
                <el-card v-for="(item, index) in adGroupOptions.ttAdList" style="margin-bottom: 10px" :key="index">
                  <div slot="header" class="clearfix">
                    <span></span>
                    <el-button v-show="adGroupOptions.creativeMaterialMode === 'CUSTOM'"
                               style="float: right; padding: 3px 0;color: #F56C6C; margin-left: 10px" type="text"
                               @click="delAd(index)">删除
                    </el-button>
                    <el-button style="float: right; padding: 3px 0" type="text" @click="editAd(item)">修改</el-button>
                  </div>
                  <el-descriptions :column="1">
                    <el-descriptions-item label="广告名">{{ item.adName }}</el-descriptions-item>
                    <el-descriptions-item label="广告ID">{{ item.ttAdId }}</el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </div>
            </div>
            <template v-slot:bottom>
              <el-button slot="bottom" size="mini" @click="editAdGroupDrawer = false">取消</el-button>
              <el-button slot="bottom" size="mini" type="primary" @click="handleSaveAdGroup">保存</el-button>
            </template>
          </cs-drawer-container>
          <el-drawer
            :visible="editAdDrawer"
            :append-to-body="true"
            :modal="false"
            :close-on-click-modal="false"
            :with-header="false"
            size="46%"
            class="append-to-body"
          >
            <cs-drawer-container>
              <div class="creative-drawer-box">
                <ad-form v-if="editAdDrawer" ref="adForm" :options="adOptions"
                         :platform-app-id="options.appId" :ad-group="adGroupOptions"
                         :is-origin-account="isOriginAccount" :campaign="options"
                         :current-account-id="campaignForm.platformId"></ad-form>
              </div>
              <template v-slot:bottom>
                <el-button slot="bottom" size="mini" @click="editAdDrawer = false">取消</el-button>
                <el-button slot="bottom" size="mini" type="primary" @click="handleSaveAd">保存</el-button>
              </template>
            </cs-drawer-container>
          </el-drawer>
        </el-drawer>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import AdGroupForm from "@/views/campaign-management/components/AdGroupForm";
import {
  confirmCopyCampaign,
  createAdCampaign, getIos14Quota, getLandingPageList, saveTask,
} from "@/api/campaign-management/campaign-management";
import {getActiveAccountList} from "@/api/campaign/campaign";
import AdForm from "@/views/campaign-management/components/AdForm";
import _ from 'lodash'
import Moment from "moment";

export default {
  name: "CampaignClone",
  components: {
    CsDrawerContainer,
    AdGroupForm,
    AdForm
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object
    },
    offerId: {
      type: String
    }
  },
  created() {
    this.handleOpenDialog()
  },
  data() {
    return {
      campaignForm: {
        campaignId: '',
        campaignName: '',
        num: 1,
        platformId: '',
        budget: '',
        pageId: '',
        campaignAppProfilePageState: 'OFF',
        ios14Camppaign: false
      },
      adGroupTableData: [],
      editAdGroupDrawer: false,
      accountList: [],
      rules: {
        campaignName: [
          {required: true, message: '请输入推广系列名称', trigger: 'blur'},
        ],
        platformId: [
          {required: true, message: '请选择推广账户', trigger: 'change'}
        ]
      },
      adGroupOptions: {
        ttAdList: [],
      },
      adForm: {},
      editAdDrawer: false,
      adOptions: null,
      submitCampaignLoading: false,
      budgetModeList: [{
        label: '日预算',
        value: 'BUDGET_MODE_DAY'
      }, {
        label: '总预算',
        value: 'BUDGET_MODE_TOTAL'
      },
        {
          label: '不限预算',
          value: 'BUDGET_MODE_INFINITE'
        }],
      isOriginAccount: false,
      levelQuota: {},
      androidImage: '',
      iosImage: '',
      // 落地页列表
      landingPageList: [],
      currentTaskId: null,
      timezone: 0
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val || false)
      }
    }
  },
  methods: {
    async getActiveAccountList() {
      const {data: res} = await getActiveAccountList(this.offerId)
      this.accountList = res.data
    },
    // 初始化
    handleOpenDialog() {
      this.campaignForm.campaignName = this.options.campaignName + '-copy'
      this.campaignForm.campaignId = this.options.id
      this.campaignForm.budget = this.options.budget
      this.campaignForm.budgetMode = this.options.budgetMode
      this.campaignForm.ios14Camppaign = this.options.campaignType === 'IOS14_CAMPAIGN'
      this.campaignForm.campaignAppProfilePageState = this.options.campaignAppProfilePageState
      this.getActiveAccountList()
    },
    confirmCopyCampaign() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.options.campaignAppProfilePageState === 'ON') {
          if (!this.isOriginAccount) return this.$message.error('APPO广告只允许复制到当前账户')
          await this.getLevelQuota()
          if (this.levelQuota.campaignQuota.availableQuota === 0) return this.$message.error('应用已达到 iOS 14 专属推广系列限额。 要创建新推广系列，请删除或关闭现有的某个推广系列')
        }
        const {data: res} = await confirmCopyCampaign({
          campaignId: this.campaignForm.campaignId,
          newCampaignName: this.campaignForm.campaignName,
          platformId: this.campaignForm.platformId
        })
        this.adGroupTableData = res.data.map(item => {
          item.isEdit = '待修改'
          // 获取时区
          item.scheduleStartTime = Moment().utc().add(this.timezone, "hours").format("yyyy-MM-DD HH:mm:ss")
          item.scheduleEndTime = Moment().utc().add(this.timezone, "hours").add(14, "days").format("yyyy-MM-DD HH:mm:ss")

          if (!this.isOriginAccount) {
            item.ttAdList.forEach(ad => {
              ad.identityId = ad.adIdentityName
              ad.pageId = ''
              ad.landingPageUrl = ''
            })
          }
          return item
        })
      })
    },
    editAdGroup(row) {
      this.adGroupOptions = row
      this.editAdGroupDrawer = true
    },
    editAd(row) {
      this.adOptions = row
      this.editAdDrawer = true
    },
    handleSaveAd() {
      this.$refs.adForm.$refs.adForm.validate(valid => {
        if (!valid) return
        if (this.adOptions.creativeMaterialMode === 'DYNAMIC') {
          if (this.$refs.adForm.adForm.callToActionType == '0' && this.$refs.adForm.acoCTAs.length === 0) return this.$message.error('CTA不能为空')
          const ttAdList = []
          let step = 1
          this.$refs.adForm.acoCreatives.forEach(creative => {
            this.$refs.adForm.acoAdTexts.forEach(text => {
              if (this.$refs.adForm.adForm.callToActionType === '1') {
                ttAdList.push(
                  {
                    "adName": creative.name + "-" + (step++),
                    "identityId": this.$refs.adForm.adForm.identityId,
                    "autoCreateType": this.$refs.adForm.adForm.autoCreateType,
                    "adFormat": this.$refs.adForm.adForm.adFormat,
                    "callToActionType": this.$refs.adForm.adForm.callToActionType,
                    "impressionTrackingUrl": this.$refs.adForm.adForm.impressionTrackingUrl,
                    "clickTrackingUrl": this.$refs.adForm.adForm.clickTrackingUrl,
                    "creativeList": this.$refs.adForm.adForm.creativeList,
                    "adText": text,
                    "callToAction": '',
                    "adIdentityName": this.$refs.adForm.adForm.adIdentityName,
                    "creativeId": creative.id,
                    "creativeType": creative.type,
                    "platformId": this.$refs.adForm.adForm.platformId,
                    "landingPageUrl": this.$refs.adForm.adForm.landingPageUrl,
                    "imageUrl": this.$refs.adForm.adForm.imageUrl,
                    "pageId": this.$refs.adForm.adForm.pageId,
                    "creativeUrl": creative.creativeUrl
                  }
                )
              } else {
                this.$refs.adForm.acoCTAs.forEach(cta => {
                  ttAdList.push(
                    {
                      "adName": creative.name + "-" + (step++),
                      "identityId": this.$refs.adForm.adForm.identityId,
                      "autoCreateType": this.$refs.adForm.adForm.autoCreateType,
                      "adFormat": this.$refs.adForm.adForm.adFormat,
                      "callToActionType": this.$refs.adForm.adForm.callToActionType,
                      "impressionTrackingUrl": this.$refs.adForm.adForm.impressionTrackingUrl,
                      "clickTrackingUrl": this.$refs.adForm.adForm.clickTrackingUrl,
                      "creativeList": this.$refs.adForm.adForm.creativeList,
                      "adText": text,
                      "callToAction": cta,
                      "adIdentityName": this.$refs.adForm.adForm.adIdentityName,
                      "creativeId": creative.id,
                      "creativeType": creative.type,
                      "platformId": this.$refs.adForm.adForm.platformId,
                      "landingPageUrl": this.$refs.adForm.adForm.landingPageUrl,
                      "imageUrl": this.$refs.adForm.adForm.imageUrl,
                      "pageId": this.$refs.adForm.adForm.pageId,
                      "creativeUrl": creative.creativeUrl
                    }
                  )
                })
              }
            })
          })
          console.log('tt', ttAdList)
          this.adGroupOptions.ttAdList = ttAdList
          this.adGroupOptions.acoCreatives = this.$refs.adForm.acoCreatives
          this.adGroupOptions.acoCTAs = this.$refs.adForm.acoCTAs
          this.adGroupOptions.acoAdTexts = this.$refs.adForm.acoAdTexts
        } else {
          this.adOptions.adName = this.$refs.adForm.adForm.adName
          this.adOptions.identityId = this.$refs.adForm.adForm.identityId
          this.adOptions.autoCreateType = this.$refs.adForm.adForm.autoCreateType
          this.adOptions.adFormat = this.$refs.adForm.adForm.adFormat
          this.adOptions.callToActionType = this.$refs.adForm.adForm.callToActionType
          this.adOptions.impressionTrackingUrl = this.$refs.adForm.adForm.impressionTrackingUrl
          this.adOptions.clickTrackingUrl = this.$refs.adForm.adForm.clickTrackingUrl
          this.adOptions.creativeList = this.$refs.adForm.adForm.creativeList
          this.adOptions.adText = this.$refs.adForm.adForm.adText
          this.adOptions.callToAction = this.$refs.adForm.adForm.callToAction
          this.adOptions.adIdentityName = this.$refs.adForm.adForm.adIdentityName
          this.adOptions.creativeId = this.$refs.adForm.adForm.creativeId
          this.adOptions.platformId = this.$refs.adForm.adForm.platformId
          this.adOptions.landingPageUrl = this.$refs.adForm.adForm.landingPageUrl
          this.adOptions.pageId = this.$refs.adForm.adForm.pageId
          this.adOptions.creativeType = this.$refs.adForm.adForm.creativeType
          this.adOptions.creativeUrl = this.$refs.adForm.adForm.creativeUrl
          this.adOptions.imageUrl = this.$refs.adForm.adForm.imageUrl
        }
        this.adGroupOptions.isEditAd = true
        this.$set(this.adGroupOptions, 'isEdit', '已保存')
        this.editAdDrawer = false
        this.saveDraft()
      })

    },
    handleSaveAdGroup() {
      this.$refs.adGroupForm.$refs.adGroupForm.validate(valid => {
        if (!valid) return
        this.adGroupOptions.adgroupName = this.$refs.adGroupForm.adGroupForm.adgroupName
        this.adGroupOptions.placementType = this.$refs.adGroupForm.adGroupForm.placementType
        this.adGroupOptions.commentDisabled = this.$refs.adGroupForm.adGroupForm.commentDisabled
        this.adGroupOptions.videoDownloadDisabled = this.$refs.adGroupForm.adGroupForm.videoDownloadDisabled
        this.adGroupOptions.creativeMaterialMode = this.$refs.adGroupForm.adGroupForm.creativeMaterialMode
        this.adGroupOptions.gender = this.$refs.adGroupForm.adGroupForm.gender
        this.adGroupOptions.actionPeriod = this.$refs.adGroupForm.adGroupForm.actionPeriod
        this.adGroupOptions.expansionEnabled = this.$refs.adGroupForm.adGroupForm.expansionEnabled
        this.adGroupOptions.budgetMode = this.$refs.adGroupForm.adGroupForm.budgetMode
        this.adGroupOptions.budget = this.$refs.adGroupForm.adGroupForm.budget
        this.adGroupOptions.scheduleType = this.$refs.adGroupForm.adGroupForm.scheduleType
        this.adGroupOptions.scheduleEndTime = this.$refs.adGroupForm.adGroupForm.scheduleEndTime
        this.adGroupOptions.scheduleStartTime = this.$refs.adGroupForm.adGroupForm.scheduleStartTime
        this.adGroupOptions.optimizationGoal = this.$refs.adGroupForm.adGroupForm.optimizationGoal
        this.adGroupOptions.optimizationEvent = this.$refs.adGroupForm.adGroupForm.optimizationEvent
        this.adGroupOptions.bidType = this.$refs.adGroupForm.adGroupForm.bidType
        this.adGroupOptions.roasBid = this.$refs.adGroupForm.adGroupForm.roasBid
        this.adGroupOptions.bidPrice = this.$refs.adGroupForm.adGroupForm.bidPrice
        this.adGroupOptions.conversionBidPrice = this.$refs.adGroupForm.adGroupForm.conversionBidPrice
        this.adGroupOptions.dailyRetentionRatio = this.$refs.adGroupForm.adGroupForm.dailyRetentionRatio
        this.adGroupOptions.pacing = this.$refs.adGroupForm.adGroupForm.pacing
        this.adGroupOptions.platformId = this.$refs.adGroupForm.adGroupForm.platformId
        this.adGroupOptions.appId = this.$refs.adGroupForm.adGroupForm.appId
        this.adGroupOptions.shareDisabled = this.$refs.adGroupForm.adGroupForm.shareDisabled
        this.adGroupOptions.interestCategory = JSON.stringify(this.$refs.adGroupForm.adGroupForm.interestCategory)
        this.adGroupOptions.interestsByKeyword = JSON.stringify(this.$refs.adGroupForm.adGroupForm.interestsByKeyword)
        this.adGroupOptions.videoUserActions = JSON.stringify(this.$refs.adGroupForm.adGroupForm.videoUserActions)
        this.adGroupOptions.videoRelatedCategory = JSON.stringify(this.$refs.adGroupForm.adGroupForm.videoRelatedCategory)
        this.adGroupOptions.creatorRelatedCategory = JSON.stringify(this.$refs.adGroupForm.adGroupForm.creatorRelatedCategory)
        this.adGroupOptions.householdIncome = this.$refs.adGroupForm.adGroupForm.householdIncome.join(',')
        this.adGroupOptions.locationIds = this.$refs.adGroupForm.adGroupForm.locationIds.join(',')
        this.adGroupOptions.placement = this.$refs.adGroupForm.adGroupForm.placement.join(',')
        this.adGroupOptions.age = this.$refs.adGroupForm.adGroupForm.age.join(',')
        this.adGroupOptions.languages = this.$refs.adGroupForm.adGroupForm.languages.join(',')
        this.adGroupOptions.interestCategoryIds = this.$refs.adGroupForm.adGroupForm.interestCategoryIds.join(',')
        this.adGroupOptions.interestsByKeywordIds = this.$refs.adGroupForm.adGroupForm.interestsByKeywordIds.join(',')
        this.adGroupOptions.videoRelatedCategoryIds = this.$refs.adGroupForm.adGroupForm.videoRelatedCategoryIds.join(',')
        this.adGroupOptions.creatorRelatedCategoryIds = this.$refs.adGroupForm.adGroupForm.creatorRelatedCategoryIds.join(',')
        this.adGroupOptions.expansionTypes = this.$refs.adGroupForm.adGroupForm.expansionTypes.join(',')
        this.adGroupOptions.isEdit = '已保存'
        this.editAdGroupDrawer = false
        this.saveDraft()
      })
    },
    async submitForm() {
      if (this.submitCampaignLoading) return
      if (this.adGroupTableData.some(adGroup => {
        return adGroup.ttAdList.some(ad => ad.pageId === '')
      }) && this.options.campaignAppProfilePageState === 'ON') return this.$message.error('广告未指定应用介绍页')
      this.submitCampaignLoading = true
      const adGroups = this.adGroupTableData.map(item => {
        if (item.videoUserActions === '') {
          item.videoUserActions = {
            VIDEO_RELATED: [],
            CREATOR_RELATED: []
          }
        } else {
          item.videoUserActions = JSON.parse(item.videoUserActions)
        }
        const actionScene = []
        if (item.videoUserActions.VIDEO_RELATED.length) {
          actionScene.push('VIDEO_RELATED')
        }
        if (item.videoUserActions.CREATOR_RELATED.length) {
          actionScene.push('CREATOR_RELATED')
        }
        const ttAdList = item.ttAdList.map(ad => {
          return {
            "adName": ad.adName,
            "adText": ad.adText,
            "adFormat": ad.adFormat,
            "callToActionType": ad.callToActionType,
            "callToAction": ad.callToAction,
            "clickTrackingUrl": ad.clickTrackingUrl,
            "creativeId": ad.creativeId,
            "impressionTrackingUrl": ad.impressionTrackingUrl,
            "operationStatus": "DISABLE",
            "identityType": "CUSTOMIZED_USER",
            "identityId": ad.identityId,
            "adIdentityName": ad.adIdentityName,
            "proportion": ad.proportion,
            "creativeType": ad.creativeType,
            "landingPageUrl": ad.landingPageUrl,
            "pageId": ad.pageId,
            "imageUrl": ad.imageUrl
          }
        })
        return {
          "adgroupName": item.adgroupName,
          "age": item.age,
          "gender": item.gender,
          "languages": item.languages,
          "locationIds": item.locationIds,
          "appId": item.appId,
          "autoTargetingEnabled": item.autoTargetingEnabled,
          "bidType": item.bidType,
          "budget": item.budget,
          "budgetMode": item.budgetMode,
          "commentDisabled": item.commentDisabled,
          "householdIncome": item.householdIncome,
          "optimizationEvent": item.optimizationEvent,
          "optimizationGoal": item.optimizationGoal,
          "pacing": item.pacing,
          "placementType": item.placementType,
          "scheduleStartTime": item.scheduleStartTime,
          "scheduleEndTime": item.scheduleEndTime,
          "scheduleType": item.scheduleType,
          "videoDownloadDisabled": item.videoDownloadDisabled,
          "blockedPangleDisabled": item.blockedPangleDisabled,
          "placement": item.placement,
          "interestCategoryIds": item.interestCategoryIds,
          "interestCategory": item.interestCategory,
          "operationStatus": "DISABLE",
          "platformId": item.platformId,
          "billingEvent": item.billingEvent,
          "dailyRetentionRatio": item.dailyRetentionRatio,
          "os": item.os,
          "deepBidType": item.deepBidType,
          "roasBid": item.roasBid,
          "audienceIds": item.audienceIds,
          "excludedAudienceIds": item.excludedAudienceIds,
          "expansionEnabled": item.expansionTypes.length > 0 ? 1 : 0,
          "expansionTypes": item.expansionTypes,
          "videoUserActions": JSON.stringify(item.videoUserActions),
          "actionPeriod": item.actionPeriod,
          "creatorRelatedCategoryIds": item.creatorRelatedCategoryIds,
          "creatorRelatedCategory": item.creatorRelatedCategory,
          "videoRelatedCategoryIds": item.videoRelatedCategoryIds,
          "videoRelatedCategory": item.videoRelatedCategory,
          "creativeMaterialMode": item.creativeMaterialMode,
          "interestsByKeyword": item.interestsByKeyword,
          "interestsByKeywordIds": item.interestsByKeywordIds,
          "bidPrice": item.bidPrice,
          "conversionBidPrice": item.conversionBidPrice,
          "actionScene": actionScene.join(','),
          "shareDisabled": item.shareDisabled,
          ttAdList
        }
      })
      const campaign = {
        "budget": this.options.budget,
        "budgetMode": this.options.budgetMode,
        "budgetOptimizeSwitch": this.options.budgetOptimizeSwitch,
        "campaignName": this.campaignForm.campaignName,
        "campaignType": this.options.campaignType,
        "objectiveType": this.options.objectiveType,
        "operationStatus": "DISABLE",
        "platformId": this.campaignForm.platformId,
        "offerId": this.offerId,
        "appName": this.options.appName,
        "appId": this.options.appId,
        "os": this.options.os,
        "campaignAppProfilePageState": this.options.campaignAppProfilePageState
      }
      await createAdCampaign({
        campaign,
        adGroups,
      }).finally(() => {
        this.submitCampaignLoading = false
      })

      // console.log({
      //   campaign,
      //   adGroups,
      // })
      this.$message.success('复制成功')
      this.dialogVisible = false
    },
    delAdGroup(index) {
      this.adGroupTableData.splice(index, 1)
    },
    delAd(index) {
      this.adGroupOptions.ttAdList.splice(index, 1)
    },
    handleChangePlatform(val) {
      this.isOriginAccount = this.options.platformId === val
      // getLandingPageList(val)
      const account = this.accountList.find(item => item.platformId === val)
      // 获取时区
      this.timezone = account.timezoneOffset
      if (this.adGroupTableData.length > 0) {
        this.adGroupTableData.forEach(adGroup => {
          adGroup.scheduleStartTime = Moment().utc().add(this.timezone, "hours").format("yyyy-MM-DD HH:mm:ss")
          adGroup.scheduleEndTime = Moment().utc().add(this.timezone, "hours").add(14, "days").format("yyyy-MM-DD HH:mm:ss")
        })
      }
      this.saveDraft()
    },
    async getLevelQuota() {
      const {data: res} = await getIos14Quota({
        appId: this.options.appId,
        platformId: this.campaignForm.platformId
      })
      this.levelQuota = res.data
    },
    async handleChangeIos14Switch(val) {
      if (val) {
        const {data: res} = await getIos14Quota({
          appId: this.options.appId,
          platformId: this.campaignForm.platformId
        })
        if (res.data.campaignQuota.availableQuota < 1) {
          this.campaignForm.ios14Camppaign = false
          this.campaignForm.campaignAppProfilePageState = 'OFF'
          return this.$message.error('应用已达到 iOS 14 专属推广系列限额。 要创建新推广系列，请删除或关闭现有的某个推广系列')
        } else {
          this.levelQuota = res.data
        }
      }
    },
    handleChangeLandingPage(val) {
      const page = this.landingPageList.find(item => item.value === val)
      this.campaignForm.landingPageUrl = page.landingPageUrl
      this.campaignForm.imageUrl = page.imageUrl
    },
    async getLandingPageList(platformId) {
      const {data: res} = await getLandingPageList(platformId)
      this.landingPageList = res.data
    },
    // 保存草稿
    async saveDraft() {
      const {data: res} = await saveTask({
        offerId: this.offerId,
        id: this.currentTaskId,
        name: this.campaignForm.campaignName,
        sourceData: JSON.stringify({
          mode: 1,
          options: this.options,
          adGroupTableData: this.adGroupTableData,
          campaignForm: this.campaignForm
        })
      })
      // this.$message.success('保存草稿成功')
      this.currentTaskId = res.data.id
    },
    setAdGroupTableData(data) {
      this.adGroupTableData = data
    },
    setCurrentTaskId(id) {
      this.currentTaskId = id
    },
    setCampaignForm(form) {
      this.campaignForm = form
    },
    handleChangeName: _.debounce(function () {
      console.log(this)
      this.saveDraft()
    }, 500)
  }
}
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}

.copy-campaign {
  ::v-deep .el-dialog {
    margin: 0 0 0 216px;
    width: calc(100vw - 220px);
    background: #fff0;
  }

  ::v-deep .el-drawer {
    top: unset;
    height: calc(100vh - 114px);
  }

  ::v-deep .el-dialog__header {
    padding: unset;
  }

  ::v-deep .el-dialog__body {
    padding: unset;
  }

  .root {
    height: calc(100vh - 115px);
    overflow: auto;
    display: flex;

    .campaign-card {
      height: 100%;
      width: 500px;

      .campaign-card-wrapper {
        ::v-deep .el-card__header {
          border-top: 1px solid #999;
          border-right: 1px solid #999;
          border-left: 1px solid #999;
        }

        ::v-deep .el-card__body {
          border-right: 1px solid #999;
          border-bottom: 1px solid #999;
          border-left: 1px solid #999;
        }
      }
    }

    .edit-ad-group-box {
      display: flex;
      height: 100%;

      .edit-ad-group-box-left {
        width: 70%;
        overflow: auto;
      }

      .edit-ad-group-box-right {
        width: 30%;
        overflow: auto;
        padding: 20px;
      }
    }
  }
}

.append-to-body {
  ::v-deep .el-drawer {
    top: unset;
    height: calc(100vh - 114px);
  }
}
</style>
